package com.loop.unclelend.utils.dialog

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.loop.unclelend.MyApplication
import com.loop.unclelend.R
import com.loop.unclelend.databinding.UncleDialogKefuBinding
import com.loop.unclelend.pro.ProDialog
import com.loop.unclelend.ui.adapter.Adapter_Kefu
import com.loop.unclelend.utils.ToastManager
import com.loop.unclelend.utils.adapter.UncleOnItemChildClickListener
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.CustomConfigsHelper
import com.loop.unclelend.utils.permission.OnPermissionCallback
import com.loop.unclelend.utils.permission.Permission
import com.loop.unclelend.utils.permission.XXPermissions
import org.json.JSONObject

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/14 15:41
 * @Annotation：提示dialog
 */
class Dialog_Kefu(context: Context?) : ProDialog(context) {

    lateinit var binding: UncleDialogKefuBinding
    private var callback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //客服联系方式列表
    private var kefuAdapter: Adapter_Kefu? = null

    override fun getRootView(): View {
        binding = UncleDialogKefuBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initUncleRecyclerView()
    }

    override fun initListener() {
        setOnClickListener(binding.imgClose)
    }

    override fun initData() {
        setUncleKefuContactData()
    }

    override fun onViewClick(v: View?) {
        dismiss()
    }

    /**
     * 事件备注
     */
    fun setUncleKefuRemark(remark: String): Dialog_Kefu{
        this.eventRemark = remark
        return this
    }

    /**
     * 设置监听回调
     */
    fun setUncleKefuCallback(callback: IDialogCallback): Dialog_Kefu{
        this.callback = callback
        return this
    }

    fun setUncleCancelable(flag: Boolean): Dialog_Kefu{
        setCancelable(flag)
        return this
    }

    fun setUncleCanceledOnTouchOutside(flag: Boolean): Dialog_Kefu{
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化Tab列表
     */
    private fun initUncleRecyclerView() {
        binding.recyclerView.visibility = View.GONE
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        kefuAdapter = Adapter_Kefu(binding.recyclerView)
        binding.recyclerView.adapter = kefuAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        kefuAdapter!!.setOnItemChildClickListener(UncleOnItemChildClickListener { _, childView, position ->
            val item = kefuAdapter!!.getItem(position)
            if (childView.id == R.id.btn_fun) {//切换item
                when (item.optString("type")) {
                    "MOBILE" -> {//电话
                        if (XXPermissions.isGranted(context, Permission.CALL_PHONE)) {
                            onCallAction(item)
                        } else {
                            XXPermissions.with(context)
                                .permission(Permission.CALL_PHONE)
                                .request(object : OnPermissionCallback {
                                    override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_PERMISSION_SYSTEM_AGREE, Permission.CALL_PHONE)
                                        onCallAction(item)
                                    }

                                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_PERMISSION_SYSTEM_DENY, Permission.CALL_PHONE)
                                        XXPermissions.startPermissionActivity(context, Permission.CALL_PHONE)
                                    }
                                })
                        }
                    }

                    else -> {//邮箱
                        onCopyAction(item)
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    @SuppressLint("SetTextI18n")
    private fun setUncleKefuContactData(){
        binding.txtWorkTime.visibility = View.VISIBLE
        binding.recyclerView.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = CustomConfigsHelper.getUncleConfigData()
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                contactList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                contactList.add(obj)
            }
        }
        kefuAdapter!!.data = contactList


        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        val customData = CustomConfigsHelper.getUncleCustomData()
        if (customData != null){
            if (!customData.has("workDate") || !customData.has("workTime")){
                val commonCustomData = CustomConfigsHelper.getUncleCustomData()
                if (commonCustomData != null) {
                    customData.put("workDate",commonCustomData.optString("workDate"))
                    customData.put("workTime",commonCustomData.optString("workTime"))
                }
            }
            workDate = customData.optString("workDate")
            workTime = customData.optString("workTime")
        }
        binding.txtWorkTime.text = "$workDate,$workTime"
    }

    /**
     * 复制
     */
    private fun onCopyAction(item: JSONObject){
        val type = item.optString("type")
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_FEEDBACK_COPY,type + "：" + item.optString("value"))
        // 获取剪贴板管理器
        val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", item.optString("value"))
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        ToastManager.showShortText(context,MyApplication.app.getString(R.string.dialog_kefu_copy_success))
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject){
        val type = item.optString("type")
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_FEEDBACK_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        context.startActivity(callIntent)
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    override fun onStart() {
        super.onStart()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.DIALOG.UNCLE_DIALOG_KEFU_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.DIALOG.UNCLE_DIALOG_KEFU_DISMISS,eventRemark)
    }
}